#!/bin/bash
defaultRegistry=edge.local.io:5000

helpString="
docker-registry operation

usages: ./dr.sh list|rm|help
-----------------------------------------------------------------------------------------------------
list [registry]            list all <image:tag> in registry, default registry is ${defaultRegistry}
                           example: ./dr.sh list, ./dr.sh list ${defaultRegistry}

rm <registry/image:tag>    delete image:tag, format: registry/image:tag
                           example: ./dr.sh rm ${defaultRegistry}/pause:3.4.1

help                       show help info\n
"

cmd=$1
if [ -z "$cmd" ]; then
  cmd="help"
fi

args=$2

list() {
  local registry=$1
  if [ -z "$registry" ]; then
    registry=${defaultRegistry}
  fi
  local images=$(curl -ks http://$registry/v2/_catalog | jq .repositories[] | sed 's/"//g')
  for i in $images; do
    local tags=$(curl -ks http://$registry/v2/$i/tags/list | grep -v :null | jq .tags[] | sed 's/"//g')
    for j in $tags; do
      echo "$registry/$i:$j"
    done
  done
}

remove() {
  local imageFullName=$1
  local imagePrefix=${imageFullName%:*}
  local registryName=${imagePrefix%%/*}
  local delImage=${imagePrefix#*/}
  local delTag=${imageFullName##*:}
  local digest=$(curl --header "Accept: application/vnd.docker.distribution.manifest.v2+json" -I http://$registryName/v2/$delImage/manifests/$delTag | grep Etag | awk -F '"' '{print $2}')
  echo "delete $delImage:$delTag from $registryName, digest=$digest"
  echo "curl  -X DELETE http://$registryName/v2/$delImage/manifests/$digest"
  curl -X DELETE http://$registryName/v2/$delImage/manifests/$digest
}

case $cmd in
  "list")
    list $args
    ;;

  "rm")
    if [ -z "$args" ]; then
      echo "rm <image:tag>"
    else
      remove $args
    fi
    ;;
  "help")
    echo "$helpString"
    ;;
esac

